<template>
  <div class="app-container">
    <div id="report" v-if="currentTableRow">
      <div class="title">
        <div style="width: 716px; height: auto">
          <div class="center size-24">技转试做任务单</div>
          <table class="center size-18">
            <tr>
              <td class="width50">型体</td>
              <td class="width80" colspan="2" rowspan="4">
                <img class="img_out" :src="currentTableRow.photoPath" />
              </td>
              <td class="width30">鞋码</td>
              <td class="widthSize" v-for="item in sizes">{{ item }}</td>
            </tr>
            <tr>
              <td class="width50">{{ currentTableRow.styleNo }}</td>
              <td class="width30">冲刀号</td>
              <td class="widthSize" v-for="item in cuts">{{ item }}</td>
            </tr>
            <tr>
              <td class="width50">配色</td>
              <td class="width30">楦头号</td>
              <td class="widthSize" v-for="item in lasts">{{ item }}</td>
            </tr>
            <tr>
              <td class="width50">{{ currentTableRow.styleColor }}</td>
              <td class="width30">大底号</td>
              <td class="widthSize" v-for="item in soles">{{ item }}</td>
            </tr>
            <tr>
              <td class="width50">{{ currentTableRow.cfmDate }}</td>
              <td class="width45">阶段</td>
              <td class="width45">类型</td>
              <td class="width30">计划日</td>
              <td class="widthSize" v-for="item in soles"></td>
            </tr>
          </table>
          <table class="center size-18">
            <tr v-for="item in selectedLists3">
              <td class="width50">
                <img class="img_code" :src="item.qrCodeData" />
              </td>
              <td class="width45">{{ item.stage }}</td>
              <td class="width45">{{ item.typeName }}</td>
              <td class="width30">{{ item.planDate }}</td>
              <td class="widthSize" v-for="item2 in item.arr">{{ item2 }}</td>
            </tr>
          </table>
        </div>
      </div>
    </div>

    <Find :OriginalFilter="{ static: true }" :formList="formList" @findClicked="findClicked" />

    <div class="flex mt10" style="width: 100%; background-color: white">
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
        <h1 class="f16">任务建档</h1>
        <Table
          :tableHeader="tableHeader"
          :tableData="tableData"
          selection
          class="mt10"
          :isLoading="isLoading"
          :isSingleSelect="true"
          @selectList="selectTableList"
          @currentRow="currentRow"
        />
        <PageModule
          :PageData="{ total, pageSizeShow: true, buttonS: true }"
          :layout="'prev, pager'"
          @pageSizeChange="handleSizeChange"
          @pageChange="handleCurrentChange"
        />
      </el-card>
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
        <!-- <h1 class="f16">节假日定义</h1> -->
        <Table :tableHeader="tableHeader2" :tableData="tableData2" class="mt10" :isLoading="isLoading2" :TableHeight="50" />
        <el-button class="primaryBth mt10" type="primary" size="default" @click="printPdf">勾选打任务单</el-button>
        <el-button class="primaryBth mt10" type="primary" size="default" @click="reWrite">当前行重做</el-button>

        <JTable
          :tableHeader="tableHeader3"
          :tableData="tableData3"
          :isLoading="isLoading2"
          :isSingleSelect="true"
          @selectList="selectTableList3"
          selection
          :TableHeight="50"
          @currentRow="currentRow3"
          @confirmChange="confirmChange3"
          @inputChange="inputChange3"
        />
      </el-card>
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }" class="mt10">
        <!-- <h1 class="f16">节假日定义</h1> -->
      </el-card>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import LoginWork from '@/utils/LoginWork'
import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'TaskFiling'
})
</script>

<script lang="ts" setup>
import { i18n, Jzhcn } from '@/i18n'
import { computed, ref } from 'vue'
import { ElMessage } from 'element-plus'
import service from '@/utils/request'
import { debounce, split } from 'lodash'
import { onMounted, watch } from 'vue'
import qrcode from 'qrcode'
import pdf from './printTaskFiling.vue'
const soles = ref([])
const lasts = ref([])
const sizes = ref([])
const cuts = ref([])

const printShow = ref(false)
const printArr = ref([]) as any
const printPdf = () => {
  if (selectedLists3.value.length === 0) {
    JMessage.error('请先勾选数据')
    return
  }
  selectedLists3.value.forEach((item: any) => {
    item.arr = []
    let qrCodeData = item.taskNo
    qrcode.toDataURL(qrCodeData, (err: any, url: any) => {
      if (err) {
        JMessage.error(err)
      } else {
        qrCodeData = url
      }
    })
    item.qrCodeData = qrCodeData
    for (let index = 0; index < sizes.value.length; index++) {
      item.arr.push(item[sizes.value[index]])
    }
  })
  console.log(selectedLists3.value)

  setTimeout(() => {
    // const printWindow = window.open('', '_blank')
    const printHTML = (document.querySelector('#report') as any).innerHTML
    window.document.body.innerHTML = printHTML
    window.print() // 调用浏览器的打印功能打印指定区域
    window.location.reload() // 打印完成后重新加载页面

    // const qrCodeContainer = document.querySelector('#report') as any
    // qrCodeContainer.style.display = 'block'
    // printWindow!.document.write(`
    //   <!DOCTYPE html>
    //   <html>
    //     <head>
    //       <title>打印指令领料作业</title>
    //       <link rel="stylesheet" type="text/css" href="print.css" media="print">
    //       <style>
    //         body, html {
    //           margin: 0;
    //           padding: 0;
    //         }
    //         @page {
    //           size: auto;
    //           margin: 3mm;
    //         }
    //         @media print {
    //         }
    //         h2 {
    //           margin-left: initial; /* 或者设置适合打印的左边距 */
    //           page-break-inside: avoid; /* 避免在h2元素内部分页 */
    //         }
    //         .title {
    //             display: flex;
    //             justify-content: center;
    //             font-size: 6px;
    //         }
    //         .center {
    //             text-align: center;
    //         }

    //         .right {
    //             text-align: right;
    //         }

    //         .left {
    //             text-align: left;
    //         }

    //         .no-padding {
    //             padding: 0;
    //         }

    //         .no-margin {
    //             margin: 0;
    //         }

    //         .margin-5 {
    //             margin: 5px;
    //         }

    //         .margin-top-5 {
    //             margin-top: 5px;
    //         }

    //         .margin-top-15 {
    //             margin-top: 15px;
    //         }

    //         .size-8 {
    //             font-size: 8px !important;
    //         }

    //         .size-10 {
    //             font-size: 10px;
    //         }

    //         .size-12 {
    //             font-size: 12px;
    //         }

    //         .size-14 {
    //             font-size: 14px;
    //         }

    //         .size-16 {
    //             font-size: 16px;
    //         }

    //         .size-18 {
    //             font-size: 18px;
    //         }

    //         .size-24 {
    //             font-size: 24px;
    //         }

    //         #date-tip {
    //             position: relative;
    //         }

    //         span.tip {
    //             display: inline-block;
    //             height: 14px;
    //             line-height: 14px;
    //             margin-right: 30px;
    //         }

    //         table {
    //             font-size: 10px;
    //             border-collapse: collapse;
    //             border-spacing: 0;
    //             border-collapse: collapse;
    //             border-spacing: 0;
    //             empty-cells: show;
    //             width: 100%;
    //         }

    //         table th,
    //         table td {
    //             border: 1px solid #000;
    //             font-size: 12px;
    //         }

    //         table.no-border,
    //         table.no-border th,
    //         table.no-border td {
    //             border: 0px;
    //         }

    //         table td.no-left-border {
    //             border-left: 0px;
    //         }

    //         table td.no-right-border {
    //             border-right: 0px;
    //         }

    //         .img_out {
    //             width: 70px;
    //             height: 70px;
    //             max-height: 70px;
    //             object-fit: contain;
    //             overflow: hidden;
    //         }

    //         .img_code {
    //             width: 60px;
    //             height: 60px;
    //             max-width: 60px;
    //             max-height: 60px;
    //             object-fit: contain;
    //         }

    //         .width50 {
    //             width: 70px;
    //             max-width: 70px;
    //         }

    //         .width30 {
    //             width: 40px;
    //             max-width: 40px;
    //         }

    //         .width45 {
    //             width: 35px;
    //             max-width: 35px;
    //         }

    //         .width80 {
    //             width: 70px;
    //             max-width: 70px;
    //         }

    //         .widthSize {
    //             width: 20px;
    //             min-width: 20px;
    //             max-width: 20px;

    //         }
    //       </style>
    //     </head>
    //     <body>
    // `)

    // const cloneContainer = qrCodeContainer.cloneNode(true)
    // printWindow!.document.body.appendChild(cloneContainer)

    // printWindow!.document.write(`
    //     </body>
    //   </html>
    // `)
    // printWindow!.document.close()
    // // 开始打印
    // printWindow!.print()
    // qrCodeContainer.style.display = 'none'
  }, 800)
}

const formList = ref([
  {
    type: 'select',
    selectValue: '',
    selectP: '品牌',
    selectOptions: []
  },
  {
    type: 'input',
    inputPlaceholder: '请输入型体',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '状态',
    selectOptions: []
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  },
  {
    type: 'button',
    checkboxLabel: '建任务'
  }
  // {
  //   type: 'button',
  //   checkboxLabel: '勾选隐藏'
  // },
  // {
  //   type: 'button',
  //   checkboxLabel: '取消隐藏'
  // }
]) as any

// 表一模块
// 表一按钮
const findClicked = async (content: string) => {
  if (content === '置空') {
    formList.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
  if (content === '勾选隐藏') {
    if (selectedLists.value.length === 0) {
      JMessage.error('请先选择数据')
      return
    }
    const res = (await LoginWork.post(`/sdStyle/optionTask?choose=${1}`, selectedLists.value)) as any
    if (res.code === 200) {
      JMessage.success('勾选隐藏成功')
      getTableList()
    } else {
      JMessage.error(res.message)
    }
  }
  if (content === '取消隐藏') {
    if (selectedLists.value.length === 0) {
      JMessage.error('请先选择数据')
      return
    }
    const res = (await LoginWork.post(`/sdStyle/optionTask?choose=${2}`, selectedLists.value)) as any
    if (res.code === 200) {
      JMessage.success('取消隐藏成功')
      getTableList()
    } else {
      JMessage.error(res.message)
    }
  }
  if (content === '建任务') {
    if (tableData3.value.length !== 0) {
      JMessage.warning('不能重复建任务')
      return
    }
    const res = (await LoginWork.post(`/sdStyle/creatTask`, currentTableRow.value)) as any
    if (res.code === 200) {
      JMessage.success('建任务成功')
      currentRow(currentTableRow.value)
    } else {
      JMessage.error(res.message)
    }
  }
}
const tableData = ref([])
const imgList = ref([])
const isLoading = ref(true)
// 分页器
const currentPage = ref(1)
const pageSize = ref(40)
const total = ref(0)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTableList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getTableList()
}
const tableHeader = ref([
  {
    type: 'img',
    label: '图片',
    prop: 'photoPath',
    srcList: imgList
  },
  {
    label: '客户',
    prop: 'custNo'
  },
  {
    label: '型体',
    prop: 'styleNo'
  },
  {
    label: '颜色',
    prop: 'styleColor'
  },
  {
    label: '冲刀',
    prop: 'cutTool'
  },
  {
    label: '楦头',
    prop: 'lastMold'
  },
  {
    label: '大底',
    prop: 'solePart'
  },
  {
    label: '大底厂商',
    prop: 'soleVendor'
  }
])
// 获取表数据
const getTableList = debounce(async () => {
  isLoading.value = true
  let tableDataList = await service.get<any, any>(
    `/sdStyle/getTaskFiling?custNo=${
      formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '品牌')?.selectValue
    }&styleNo=${
      formList.value.find(
        (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入型体'
      )?.inputValue
    }&taskState=${
      formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '状态')?.selectValue
    }&pageNum=${currentPage.value}&pageSize=${pageSize.value}`
  )
  isLoading.value = false
  imgList.value = tableDataList.list.map((item: any) => {
    return item.photoPath
  })
  tableData.value = tableDataList.list
  total.value = tableDataList.total
  currentRow()
}, 500)
onMounted(() => {
  getTableList()
})
watch(
  () =>
    formList.value.map((item: any) => {
      item.selectValue, item.inputValue, item.dateValue, item.checked
    }),
  () => {
    getTableList()
  }
)
const selectedLists = ref([])
const selectTableList = (selectedList: any, ref: any) => {
  selectedLists.value = selectedList
  currentRow(selectedList[selectedList.length - 1])
}
// 点击表给另一张表传数据
const currentTableRow = ref() as any
const currentRow = async (row: any = tableData.value[0] ? tableData.value[0] : {}) => {
  if (row === undefined) {
    row = {
      photoPath: '#',
      styleNo: ''
    }
  }
  currentTableRow.value = row
  getTableList2()
}
const currentTableRow3 = ref({}) as any
const currentRow3 = async (row: any = tableData3.value[0]) => {
  currentTableRow3.value = row
}

// 表二模块
const tableData2 = ref([])
const imgList2 = ref([])
const isLoading2 = ref(true)
// 分页器
const currentPage2 = ref(1)
const pageSize2 = ref(40)
const total2 = ref(0)
const handleSizeChange2 = (val: number) => {
  pageSize2.value = val
  getTableList2()
}
const handleCurrentChange2 = (val: number) => {
  currentPage2.value = val
  getTableList2()
}
// 获取表数据
const tableHeader2 = ref([
  {
    label: '鞋码',
    prop: 'sizes'
  },
  {
    label: '冲刀号',
    prop: 'cuts'
  },
  {
    label: '楦头号',
    prop: 'lasts'
  },
  {
    label: '大底号',
    prop: 'sole'
  }
])

const getTableList2 = debounce(async () => {
  const arr = [] as any
  isLoading2.value = true
  let tableDataList = await service.get<any, any>(
    `/sdStyle/getTaskFilingDetail?styleNo=${encodeURIComponent(currentTableRow.value.styleNo)}&styleColor=${encodeURIComponent(
      currentTableRow.value.styleColor
    )}`
  )
  soles.value = tableDataList.sole
  lasts.value = tableDataList.lasts
  sizes.value = tableDataList.sizes
  cuts.value = tableDataList.cuts
  tableDataList.sole.forEach((item: any, index: any) => {
    arr[index] = {
      ...arr[index],
      sole: item
    }
  })
  tableDataList.lasts.forEach((item: any, index: any) => {
    arr[index] = {
      ...arr[index],
      lasts: item
    }
  })
  tableDataList.sizes.forEach((item: any, index: any) => {
    arr[index] = {
      ...arr[index],
      sizes: item
    }
  })
  tableDataList.cuts.forEach((item: any, index: any) => {
    arr[index] = {
      ...arr[index],
      cuts: item
    }
  })

  // 渲染表头数据
  tableHeader3.value.splice(4, tableHeader3.value.length)
  tableDataList.sizes.forEach((item: any, index: any) => {
    tableHeader3.value.push({
      label: item,
      prop: item,
      width: 50
    })
  })
  // 渲染表内数据
  const arr2 = tableDataList.list.map((item: any, index: any) => {
    const str = {} as any
    let count = 0
    for (let key in item) {
      if (key.includes('qty')) {
        if (item[key] === 'null') item[key] = ''
        str[tableDataList.sizes[count]] = item[key]
        count++
      }
    }
    return {
      ...item,
      ...str
    }
  })
  setTimeout(() => {
    tableData3.value = arr2.map((item: any) => {
      item.addAndUpdate = true
      item.disableConfirm = true
      item.change = 'Y'
      return item
    })
    currentRow3()
  }, 500)
  isLoading2.value = false
  tableData2.value = arr.map((item: any) => {
    // item.disableConfirm = false
    return item
  })
  total2.value = tableDataList.total
  // currentRow2()
}, 500)

const tableData3 = ref([]) as any
const tableHeader3 = ref([
  {
    change: true,
    label: '阶段',
    prop: 'stage'
  },
  {
    change: true,
    label: '类型',
    prop: 'typeName',
    width: 50
  },
  {
    width: 120,
    type: 'dateSingle',
    label: '计划上线日',
    prop: 'planDate'
  },
  {
    label: '重做原因',
    prop: 'redoReason'
  }
]) as any
const getTableList3 = debounce(async () => {
  // isLoading2.value = true
  // let tableDataList = await service.get<any, any>(`/sdStyle/getTaskSize?taskNo=${currentTableRow.value.taskNo}`)
  // isLoading2.value = false
  // tableDataList.value.forEach((item: any) => {
  //     tableHeader3.value.push({
  //         label: item.sizeNo,
  //         prop: item.sizeNo,
  //     })
  // })
  // tableData2.value = tableDataList.list
  // total2.value = tableDataList.total
  // currentRow2()
}, 500)
const inputChange3 = async (row: any, currentLabel: any, refJ: any) => {
  let key = 0
  const arr2 = tableHeader3.value.slice(4).map((item: any) => item.prop)
  arr2.forEach((item: any, index: any) => {
    if (item === currentLabel) {
      key = index + 1
    }
  })
  const obj = {
    ...row,
    qty: row[currentLabel],
    sizeNo: currentLabel,
    styleColor: currentTableRow.value.styleColor,
    styleNo: currentTableRow.value.styleNo,
    stageType: currentTableRow3.value.stageType,
    orderType: '正单'
  }
  if (currentLabel === '重做原因') {
    obj.sizeNo = ''
    obj.orderType = '重做'
  }

  const res = (await LoginWork.post('/sdStyle/updateTaskStateQty', obj)) as any
  if (res.code === 200) {
    JMessage.success('修改成功')
    refJ.toggleRowSelection(row, true)
  } else {
    JMessage.error(res.message)
    getTableList2()
  }
}
const confirmChange3 = async (row: any, fn: any, currentLabel: any) => {
  let key = 0
  const arr2 = tableHeader3.value.slice(4).map((item: any) => item.prop)
  arr2.forEach((item: any, index: any) => {
    if (item === currentLabel) {
      key = index + 1
    }
  })
  const obj = {
    ...row,
    ['qty' + key]: row[currentLabel],
    sizeNo: currentLabel
  }
  if (currentLabel === '重做原因') {
    obj.sizeNo = ''
  }

  const res = (await LoginWork.post('/sdStyle/updateTaskStateQty', obj)) as any
  if (res.code === 200) {
    JMessage.success('修改成功')
  } else {
    JMessage.error(res.message)
    getTableList2()
  }
}
const reWrite = async () => {
  const res = (await LoginWork.post('/sdStyle/updateTaskStateQty', {
    ...currentTableRow3.value,
    choose: 1
  })) as any
  if (res.code === 200) {
    JMessage.success('修改成功')
    getTableList2()
  } else {
    JMessage.error('修改失败')
  }
}
const getSelectList = async () => {
  let res = await service.get<any, any>('/style/getCondition')
  res.custom.forEach((item: any) => {
    if (item === null || item === '') return
    formList.value
      .find((item: any) => item.type === 'select' && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '品牌')
      .selectOptions.push({
        optionValue: item,
        optionLabel: item
      })
  })
  formList.value
    .find((item: any) => item.type === 'select' && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '状态')
    .selectOptions.push(
      {
        optionValue: '4',
        optionLabel: '未隐藏'
      },
      {
        optionValue: '2',
        optionLabel: '未下'
      },
      {
        optionValue: '1',
        optionLabel: '已下'
      },
      {
        optionValue: '3',
        optionLabel: '隐藏'
      }
    )
}
onMounted(() => {
  getSelectList()
})
const selectedLists3 = ref([]) as any
const selectTableList3 = (selectedList: any) => {
  selectedLists3.value = selectedList
  console.log(selectedList)
}

// selectedLists3.value.forEach((item: any) => {
//     let qrCodeData = item.taskNo; // 替换为你需要生成二维码的数据
//     qrcode.toDataURL(qrCodeData, (err: any, url: any) => {
//         if (err) { JMessage.error(err) } else { qrCodeData = url; }
//     });
// })
</script>

<style lang="less" scoped>
#report {
  display: none;
}

.title {
  display: flex;
  justify-content: center;
  font-size: 6px;
}

// 打印样式
.center {
  text-align: center;
}

.right {
  text-align: right;
}

.left {
  text-align: left;
}

.no-padding {
  padding: 0;
}

.no-margin {
  margin: 0;
}

.margin-5 {
  margin: 5px;
}

.margin-top-5 {
  margin-top: 5px;
}

.margin-top-15 {
  margin-top: 15px;
}

.size-8 {
  font-size: 8px !important;
}

.size-10 {
  font-size: 10px;
}

.size-12 {
  font-size: 12px;
}

.size-14 {
  font-size: 14px;
}

.size-16 {
  font-size: 16px;
}

.size-18 {
  font-size: 18px;
}

.size-24 {
  font-size: 24px;
}

#date-tip {
  position: relative;
}

span.tip {
  display: inline-block;
  height: 14px;
  line-height: 14px;
  margin-right: 30px;
}

table {
  font-size: 10px;
  border-collapse: collapse;
  border-spacing: 0;
  border-collapse: collapse;
  border-spacing: 0;
  empty-cells: show;
  width: 100%;
}

table th,
table td {
  border: 1px solid #000;
  font-size: 12px;
}

table.no-border,
table.no-border th,
table.no-border td {
  border: 0px;
}

table td.no-left-border {
  border-left: 0px;
}

table td.no-right-border {
  border-right: 0px;
}

.img_out {
  width: 70px;
  height: 70px;
  max-height: 70px;
  object-fit: contain;
  overflow: hidden;
}

.img_code {
  width: 60px;
  height: 60px;
  max-width: 60px;
  max-height: 60px;
  object-fit: contain;
}

.width50 {
  width: 70px;
  max-width: 70px;
}

.width30 {
  width: 40px;
  max-width: 40px;
}

.width45 {
  width: 35px;
  max-width: 35px;
}

.width80 {
  width: 70px;
  max-width: 70px;
}

.widthSize {
  width: 20px;
  min-width: 20px;
  max-width: 20px;
}
</style>
